<template>
  <div class="departments-container">
    <div class="page-header">
      <h2>部门管理</h2>
      <el-button type="primary" @click="handleAddDepartment" size="default">
        <el-icon><component is="i-plus" /></el-icon>
        添加部门
      </el-button>
    </div>

    <!-- 搜索 -->
    <el-card class="search-card" shadow="hover">
      <el-form :model="searchForm" class="search-form">
        <el-form-item label="部门名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入部门名称"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" size="small">
            <el-icon><component is="i-search" /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch" size="small">
            <el-icon><component is="i-refresh-left" /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 部门表格 -->
    <el-card class="departments-table-card" shadow="hover">
      <el-table
        :data="departmentsData"
        style="width: 100%"
        border
        v-loading="loading"
        element-loading-text="加载中..."
      >
        <el-table-column prop="id" label="ID" width="80" fixed />
        <el-table-column prop="name" label="部门名称" width="180">
          <template #default="{ row }">
            <el-tag size="default" type="primary" effect="light">{{
              row.name
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" width="300" />
        <el-table-column prop="leader" label="负责人" width="120" />
        <el-table-column prop="phone" label="联系电话" width="150" />
        <el-table-column prop="drone_count" label="无人机数量" width="120">
          <template #default="{ row }">
            <el-tag size="small" type="success">{{ row.drone_count }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button
              type="success"
              size="small"
              @click="handleEditDepartment(row)"
              :disabled="editingId === row.id"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDeleteDepartment(row)"
              :disabled="deletingId === row.id || row.drone_count > 0"
              :title="row.drone_count > 0 ? '该部门下还有无人机，无法删除' : ''"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑部门对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加部门' : '编辑部门'"
      width="500px"
      destroy-on-close
    >
      <el-form
        :model="departmentForm"
        :rules="departmentRules"
        ref="departmentFormRef"
        label-width="100px"
        class="department-form"
      >
        <el-form-item label="部门名称" prop="name">
          <el-input
            v-model="departmentForm.name"
            placeholder="请输入部门名称"
          />
        </el-form-item>

        <el-form-item label="负责人" prop="leader">
          <el-input
            v-model="departmentForm.leader"
            placeholder="请输入负责人姓名"
          />
        </el-form-item>

        <el-form-item label="联系电话" prop="phone">
          <el-input
            v-model="departmentForm.phone"
            placeholder="请输入联系电话"
          />
        </el-form-item>

        <el-form-item label="描述" prop="description">
          <el-input
            v-model="departmentForm.description"
            type="textarea"
            rows="3"
            placeholder="请输入部门描述"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="handleSubmit"
            :loading="dialogLoading"
          >
            {{ dialogLoading ? "提交中..." : "确定" }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import axios from "axios";

export default {
  name: "Departments",
  setup() {
    const loading = ref(false);
    const dialogVisible = ref(false);
    const dialogType = ref("add"); // 'add' or 'edit'
    const dialogLoading = ref(false);
    const departmentFormRef = ref(null);
    const editingId = ref(null);
    const deletingId = ref(null);

    // 搜索表单
    const searchForm = reactive({
      name: "",
    });

    // 分页
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0,
    });

    // 部门表单
    const departmentForm = reactive({
      id: "",
      name: "",
      leader: "",
      phone: "",
      description: "",
    });

    // 表单验证规则
    const departmentRules = {
      name: [{ required: true, message: "请输入部门名称", trigger: "blur" }],
    };

    // 部门数据
    const departmentsData = ref([]);

    // 初始化
    onMounted(() => {
      fetchDepartments();
    });

    // 获取部门列表
    const fetchDepartments = async () => {
      loading.value = true;
      try {
        // 从后端API获取部门数据
        const response = await axios.get("/api/departments/list", {
          params: {
            page: pagination.currentPage,
            page_size: pagination.pageSize,
            name: searchForm.name || undefined,
          },
          headers: {
            Authorization: `Bearer ${localStorage.getItem("token")}`,
          },
        });

        if (response.data.code === 200) {
          // 添加drone_count字段，默认为0（因为后端模型中没有这个字段）
          departmentsData.value = response.data.data.items.map((dept) => ({
            ...dept,
            drone_count: 0, // 可以根据实际需求从其他API获取
          }));
          pagination.total = response.data.data.total;
        } else {
          ElMessage.error(response.data.message || "获取部门列表失败");
        }

        loading.value = false;
      } catch (error) {
        console.error("获取部门列表失败:", error);
        ElMessage.error(error.response?.data?.message || "获取部门列表失败");
        loading.value = false;
      }
    };

    // 搜索
    const handleSearch = () => {
      pagination.currentPage = 1;
      fetchDepartments();
    };

    // 重置
    const resetSearch = () => {
      searchForm.name = "";
      pagination.currentPage = 1;
      fetchDepartments();
    };

    // 分页处理
    const handleSizeChange = (size) => {
      pagination.pageSize = size;
      fetchDepartments();
    };

    const handleCurrentChange = (current) => {
      pagination.currentPage = current;
      fetchDepartments();
    };

    // 打开添加部门对话框
    const handleAddDepartment = () => {
      dialogType.value = "add";
      resetDepartmentForm();
      // 添加parent_id字段
      departmentForm.parent_id = null;
      dialogVisible.value = true;
    };

    // 打开编辑部门对话框
    const handleEditDepartment = (row) => {
      dialogType.value = "edit";
      editingId.value = row.id;
      // 复制数据，包含parent_id字段
      Object.assign(departmentForm, {
        id: row.id,
        name: row.name,
        leader: row.leader || "",
        phone: row.phone || "",
        description: row.description,
        parent_id: row.parent_id || null,
      });
      dialogVisible.value = true;
    };

    // 删除部门
    const handleDeleteDepartment = (row) => {
      if (row.drone_count > 0) {
        ElMessage.warning("该部门下还有无人机，无法删除");
        return;
      }

      ElMessageBox.confirm(`确定要删除部门「${row.name}」吗？`, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          deletingId.value = row.id;
          try {
            const response = await axios.delete(`/api/departments/${row.id}`, {
              headers: {
                Authorization: `Bearer ${localStorage.getItem("token")}`,
              },
            });

            if (response.data.code === 200) {
              ElMessage.success("删除成功");
              fetchDepartments();
            } else {
              ElMessage.error(response.data.message || "删除部门失败");
            }
          } catch (error) {
            console.error("删除部门失败:", error);
            ElMessage.error(error.response?.data?.message || "删除部门失败");
          } finally {
            deletingId.value = null;
          }
        })
        .catch(() => {
          // 取消删除
        });
    };

    // 重置部门表单
    const resetDepartmentForm = () => {
      if (departmentFormRef.value) {
        departmentFormRef.value.resetFields();
      }
      Object.assign(departmentForm, {
        id: "",
        name: "",
        leader: "",
        phone: "",
        description: "",
        parent_id: null,
      });
    };

    // 提交表单
    const handleSubmit = () => {
      departmentFormRef.value.validate(async (valid) => {
        if (valid) {
          dialogLoading.value = true;
          try {
            if (dialogType.value === "add") {
              // 添加部门
              const response = await axios.post(
                "/api/departments",
                {
                  name: departmentForm.name,
                  leader: departmentForm.leader,
                  phone: departmentForm.phone,
                  description: departmentForm.description,
                  parent_id: departmentForm.parent_id,
                },
                {
                  headers: {
                    Authorization: `Bearer ${localStorage.getItem("token")}`,
                  },
                }
              );

              if (response.data.code === 200) {
                ElMessage.success("添加成功");
              } else {
                ElMessage.error(response.data.message || "添加部门失败");
                return;
              }
            } else {
              // 更新部门
              const response = await axios.put(
                `/api/departments/${departmentForm.id}`,
                {
                  name: departmentForm.name,
                  leader: departmentForm.leader,
                  phone: departmentForm.phone,
                  description: departmentForm.description,
                  parent_id: departmentForm.parent_id,
                },
                {
                  headers: {
                    Authorization: `Bearer ${localStorage.getItem("token")}`,
                  },
                }
              );

              if (response.data.code === 200) {
                ElMessage.success("更新成功");
              } else {
                ElMessage.error(response.data.message || "更新部门失败");
                return;
              }
            }

            dialogVisible.value = false;
            fetchDepartments();
            editingId.value = null;
          } catch (error) {
            console.error("操作部门失败:", error);
            ElMessage.error(error.response?.data?.message || "操作失败");
          } finally {
            dialogLoading.value = false;
          }
        }
      });
    };

    return {
      loading,
      dialogVisible,
      dialogType,
      dialogLoading,
      departmentFormRef,
      searchForm,
      pagination,
      departmentForm,
      departmentRules,
      departmentsData,
      editingId,
      deletingId,
      handleSearch,
      resetSearch,
      handleSizeChange,
      handleCurrentChange,
      handleAddDepartment,
      handleEditDepartment,
      handleDeleteDepartment,
      handleSubmit,
    };
  },
};
</script>

<style scoped>
.departments-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 500;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  align-items: end;
}

.search-form .el-form-item {
  margin-bottom: 15px;
}

.departments-table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.department-form .el-form-item {
  margin-bottom: 20px;
}
</style>
